package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.Dishservice;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/admin/dish")
@Api(tags = "菜品管理")
public class DishController {
    @Autowired
    Dishservice dishservice;
    @Autowired
    RedisTemplate redisTemplate;
    //分页条件查询
    @GetMapping("/page")
    public Result page(DishPageQueryDTO dishDTO){
       PageResult pageResult = dishservice.page(dishDTO);
       return Result.success(pageResult);
    }
    //添加菜品和口味
    @PostMapping
    public Result sevetAndFlavor(@RequestBody DishDTO dishDTO){
        dishservice.sevetAndFlavor(dishDTO);
        //清除redis缓存中的数据 保证redis和mysql的一致性
        cleanRedis("dish_"+dishDTO.getCategoryId());
        return Result.success();

    }
    //批量删除
    @DeleteMapping
    @ApiOperation("批量删除菜品")
    public Result removeBatch(@RequestParam List<Long> ids){
        dishservice.removeBatch(ids);
        //清除redis缓存中的数据 保证redis和mysql的一致性
        cleanRedis("dish_*");
        return Result.success();
    }
    //根据ID查询
    @GetMapping("/{id}")
    public Result queryById(@PathVariable Long id){
       DishVO dishVO = dishservice.queryById(id);
       return Result.success(dishVO);
    }
    //修改菜品
    @PutMapping
    public  Result update(@RequestBody DishDTO dishDTO){
        dishservice.update(dishDTO);
        //清除redis缓存中的数据 保证redis和mysql的一致性
        cleanRedis("dish_*");
        return Result.success();
    }
    //停售起售
    @PostMapping("/status/{status}")
    public Result updateStatus(@PathVariable Integer status,Long id){
        dishservice.updateStatus(status, id);
        //清除redis缓存中的数据 保证redis和mysql的一致性
        cleanRedis("dish_*");
        return  Result.success();
    }
    //根据分类ID查询套餐菜品
    @GetMapping("/list")
    public Result listByCategoryId(Long categoryId){
        List<DishVO> dishList = dishservice.listByCategoryId(categoryId);

        return Result.success(dishList);
    }
    public void cleanRedis(String pattern){
        //清除redis缓存中的数据 保证redis和mysql的一致性
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }
}
